<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="70">
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="ruleForm.phone" placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item label="验证码" prop="message">
      <el-input v-model="ruleForm.message" placeholder="请输入验证码" />
      <el-button class="get-code" type="primary">获取验证码</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  phone: '',
  message: ''
})

const validatorPhone = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback(new Error('请输入手机号!'))
  } else if (/^(?:(?:\+|00)86)?1\d{10}$/.test(value)) {
    callback(new Error('请输入正确的手机号！'))
  } else {
    callback()
  }
}
const validatorMessage = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback(new Error('请输入验证码!'))
  } else if (!/^[\d]{6}$/.test(value)) {
    callback(new Error('请输入6位验证码!'))
  } else {
    callback()
  }
}

// 定义表单规则
const rules = reactive<FormRules<typeof ruleForm>>({
  phone: [{ required: true, validator: validatorPhone, trigger: 'blur' }],
  message: [{ required: true, validator: validatorMessage, trigger: 'blur' }]
})

const verifyPhone = () => {
  ruleFormRef.value?.validate((val) => {
    if (val) {
      // 发送登录请求
      return
    }
    //ElMessage配置了按需引入，因此不能再次导入
    ElMessage({
      message: '请重新输入！',
      type: 'warning'
    })
  })
}
defineExpose({
  verifyPhone
})
</script>

<style lang="scss" scoped></style>
